package com.lagou.edu.controller;

import com.lagou.edu.pojo.Token;
import com.lagou.edu.service.TokenService;
import com.lagou.edu.service.UserService;
import com.lagou.edu.vo.LoginReqVo;
import com.lagou.edu.vo.RegisterReqVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Random;
import java.util.UUID;

/**
 * 该类用于模拟，我们要使用共享的那些配置信息做一些事情
 */
@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/register")
    public String register(@RequestParam("email")String email,@RequestParam("password")String password,@RequestParam("code")String code) {
        RegisterReqVo registerReqVo = new RegisterReqVo();
        registerReqVo.setEmail(email);
        registerReqVo.setPassword(password);
        registerReqVo.setCode(code);
        String register = userService.register(registerReqVo);
        return register;
    }

    @PostMapping("/login")
    public String login(@RequestParam("email")String email,@RequestParam("password")String password, HttpServletResponse response) {
        LoginReqVo loginReqVo = new LoginReqVo();
        loginReqVo.setEmail(email);
        loginReqVo.setPassword(password);
        String loginstr = userService.login(loginReqVo);
        if(loginstr.equals("yes")){
            Token saveToken = null;
                    //生成token写入cookie
            Token byEmail = tokenService.findByEmail(email);
            if(null == byEmail){
                saveToken = new Token();
                saveToken.setId(Long.parseLong(new Random().nextInt()+""));
            }else {
                saveToken = byEmail;
            }
            String token = UUID.randomUUID().toString();
            saveToken.setEmail(loginReqVo.getEmail());
            saveToken.setToken(token);
            tokenService.saveToken(saveToken);
//            Cookie cookie = new Cookie(loginReqVo.getEmail(),token);
//            response.addCookie(cookie);

            String[] split = loginReqVo.getEmail().split("@");
            Cookie cookie = new Cookie(split[0],token);
        }
        return loginstr;
    }
}
